import { Order, CreateOrderRequest, CreateOrderResponse } from '../types/order';

class OrderService {
  // Create a new order
  async createOrder(request: CreateOrderRequest): Promise<CreateOrderResponse> {
    try {
      const orderNumber = `ORD-${new Date().getFullYear()}-${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`;
      const order: Order = {
        id: String(Date.now()),
        orderNumber,
        date: new Date().toISOString(),
        total: request.total,
        status: 'pending',
        paymentStatus: 'unpaid',
        items: request.items,
      };

      // Store in localStorage temporarily
      const existingOrders = this.getOrders();
      existingOrders.unshift(order);
      localStorage.setItem('website_orders', JSON.stringify(existingOrders));

      return {
        success: true,
        order,
      };
    } catch (error) {
      console.error('Error creating order:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to create order',
      };
    }
  }

  // Get all orders
  getOrders(): Order[] {
    try {
      const ordersJson = localStorage.getItem('website_orders');
      return ordersJson ? JSON.parse(ordersJson) : [];
    } catch (error) {
      console.error('Error getting orders:', error);
      return [];
    }
  }

  // Get order by ID
  getOrderById(id: string): Order | null {
    const orders = this.getOrders();
    return orders.find(order => order.id === id) || null;
  }

  // Update order payment method
  async updateOrderPayment(orderId: string, paymentMethod: string): Promise<boolean> {
    try {
      const orders = this.getOrders();
      const orderIndex = orders.findIndex(order => order.id === orderId);
      
      if (orderIndex === -1) {
        return false;
      }

      orders[orderIndex].paymentMethod = paymentMethod;
      orders[orderIndex].status = 'completed';
      orders[orderIndex].paymentStatus = 'paid';

      localStorage.setItem('website_orders', JSON.stringify(orders));
      return true;
    } catch (error) {
      console.error('Error updating order payment:', error);
      return false;
    }
  }

  // Cancel an order
  async cancelOrder(orderId: string): Promise<{ success: boolean; error?: string }> {
    try {
      const orders = this.getOrders();
      const orderIndex = orders.findIndex(order => order.id === orderId);
      
      if (orderIndex === -1) {
        return { success: false, error: 'Order not found' };
      }

      const order = orders[orderIndex];

      // Only allow cancellation of pending or unpaid orders
      if (order.status === 'completed' || order.status === 'refunded') {
        return { success: false, error: 'Cannot cancel completed or refunded orders' };
      }

      // Update order status to cancelled
      orders[orderIndex].status = 'failed'; // Using 'failed' as 'cancelled' status
      orders[orderIndex].paymentStatus = 'refunded';

      localStorage.setItem('website_orders', JSON.stringify(orders));
      return { success: true };
    } catch (error) {
      console.error('Error cancelling order:', error);
      return { 
        success: false, 
        error: error instanceof Error ? error.message : 'Failed to cancel order' 
      };
    }
  }
}

export const orderService = new OrderService();
